import { ValidationPipe } from '@nestjs/common';
import { NestFactory } from '@nestjs/core';
import { NestExpressApplication } from '@nestjs/platform-express';
import { NextFunction, Request, Response } from 'express';
import * as session from 'express-session';


import { join } from 'path';
import { AppModule } from './app.module';
import { YhErrorFilter, YhExceptionFilter, YhRequestExceptionFilter, YhTypeORMErrorFilter, /* YhErrorFilter */ } from './common/filter/exception';
import { YhLoggerService } from './shared/yhlogger.service';

// 全局中间件，只能是函数不能是类
/**
 * 
 * @param req
 * @param res
 * @param next
 */
function yhGlobalMiddleware(req: Request, res: Response, next: NextFunction) {

    next();
}

async function bootstrap() {
    const app = await NestFactory.create<NestExpressApplication>(AppModule, {
        // logger
    });
    // 日志
    // app.useLogger(app.get(YhLoggerService));
    // 开启session
    app.use(
        session({
            name: 'yh.sid',
            secret: 'yh.com',
            resave: false,
            saveUninitialized: false,
        }),
    );

    // response响应拦截器
    // app.useGlobalInterceptors(new YhResponseInterceptor());

    // 异常过滤  倒序拦截异常，越后越先拦截异常
    app.useGlobalFilters(
        new YhErrorFilter(app.get(YhLoggerService)),
        new YhTypeORMErrorFilter(app.get(YhLoggerService)),
        new YhExceptionFilter(app.get(YhLoggerService)),
        new YhRequestExceptionFilter(app.get(YhLoggerService)),
    );

    // 静态资源访问
    app.useStaticAssets(join(__dirname, 'images'), {
        prefix: '/images',
    });
    app.useStaticAssets(join(__dirname, '../download'), {
        prefix: '/download',
    });
    app.useStaticAssets(join(__dirname, '../docs'), {
        prefix: '/docs',
    });
    app.useStaticAssets(join(__dirname, '../../client', 'assets'), {
        prefix: '/assets',
    });
    
    // 全局中间件
    // app.use(yhGlobalMiddleware);

    // 开启全局管道，这样就可以全局开启class-validator验证，而不用在每个controller导入管道来验证
    app.useGlobalPipes(new ValidationPipe({
        // whitelist: true
    }));

    // 全局守卫-权限验证
    // app.useGlobalGuards(new RoleGuard());

    // 设置swagger
    /* const docOptions = new DocumentBuilder()
        // .addBearerAuth()  // 管理token
        .setTitle('资产管理API接口')
        .setDescription('资产管理API接口')
        .setVersion('1')
        .build();
    const apiDocs = SwaggerModule.createDocument(app, docOptions);
    SwaggerModule.setup('/api-docs', app, apiDocs); */

    await app.listen(32200);
}
bootstrap();
